package com.eda.commous.config;

import com.eda.commous.excecption.FLowException;
import com.eda.commous.http.ApiError;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@Slf4j
@ControllerAdvice
public class FlowExceptionHandler extends ResponseEntityExceptionHandler {

    // 对异常做处理的方法
    @ExceptionHandler(Exception.class)
    public final ResponseEntity<Object> handleFLowException(Exception ex, WebRequest request) {
        HttpHeaders headers = new HttpHeaders();
        if (ex instanceof FLowException) {
            ApiError apiError = new ApiError();
            FLowException e = (FLowException)ex;
            e.getApiError();
            return this.handleExceptionInternal(e, apiError, headers, e.getStatus(), request);
        }
        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
        return this.handleExceptionInternal(ex, null, headers, status, request);
    }

    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        if(body == null) {
            body = new ApiError(ex.getMessage()).error(ApiError.INTERNAL_ERROR);
        }
        if(body instanceof ApiError) {
            ApiError apiError = (ApiError) body;
//            apiError.setError(ApiError.INTERNAL_ERROR);
//            apiError.setMassage(ex.getMessage());
            apiError.setStatus(status.value());
            apiError.setPath(this.getRequestUri(request));
        }
        log.error("catch error: {}", ex.getMessage());
        return super.handleExceptionInternal(ex, body, headers, status, request);
    }

    private String getRequestUri(WebRequest request) {
        if(request instanceof ServletWebRequest) {
            return ((ServletWebRequest) request).getRequest().getRequestURI();
        }
        return null;
    }
}
